﻿using System;
using System.Linq;
using System.Windows.Forms;
using Sponsorship.ReadModel;
using Sponsorship.ReadModel.ListOfSponsoredChildren;
using Sponsorship.Ui.Modules.Child;
using StructureMap;

namespace Sponsorship.Ui
{
    public partial class Form1 : Form
    {
        private readonly IReadRepository _readRepository;

        public Form1(IReadRepository readRepository)
        {
            _readRepository = readRepository;
            
            InitializeComponent();
        }

        protected override void OnLoad (EventArgs e)
        {
            RefreshSponsoredChildrenList ();
            base.OnLoad (e);
        }

        private void Button1Click(object sender, EventArgs e)
        {
            //Show a submodule - in this example as a modal dialog
            ObjectFactory.GetInstance<EnterSponsoredPersonForm>().ShowDialog();
            RefreshSponsoredChildrenList ();
        }

        private void Button2Click (object sender, EventArgs e)
        {
            RefreshSponsoredChildrenList ();
        }

        // TODO: SponsoredChildrenList should probably be a separate control
        private void RefreshSponsoredChildrenList()
        {
            _sponsoredChildrenList.Items.Clear();
            var items = _readRepository.GetAll<ListOfSponsoredPersonsItemDto>().AsEnumerable().Select (GetSponsoredChildrenListItem).ToArray();
            _sponsoredChildrenList.Items.AddRange (items);
        }

        private ListViewItem GetSponsoredChildrenListItem (ListOfSponsoredPersonsItemDto dto)
        {
            var itemText = dto.Id + " --> " + dto.Name;
            if (dto.AssociatedPersons != null && dto.AssociatedPersons.Count > 0)
                itemText += " (" + string.Join (", ", dto.AssociatedPersons) + ")";
            var item = new ListViewItem (itemText);
            return item;
        }

    }
}
